<template>
  <div class="n-layout-page-header">
      <n-card :bordered="false" >
        <BasicForm @register="register"  @submit="handleSubmit" @reset="handleReset" :showAdvancedButton="false"/>
      </n-card>
  </div>
  <div>
    <n-card :bordered="false" class="mt-4 proCard">
      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"

        ref="actionRef"
        :actionColumn="actionColumn"
        @update:checked-row-keys="onCheckedRow"
      >
        <template #tableTitle>
          <n-button type="primary" @click="showUserdrawer">
            <template #icon>
              <n-icon>
                <PlusOutlined />
              </n-icon>
            </template>
            添加用户
          </n-button>
        </template>

        <template #action>
          <TableAction />
        </template>
        <template #toolbar>
          <n-button type="primary" @click="reloadTable">刷新数据</n-button>
        </template>
      </BasicTable>
    </n-card>
    <n-drawer v-model:show="showdrawer" :width="600">
    <n-drawer-content :title="titledrawer" closable>
      <n-form
        :model="formParams"
        :rules="rules"
        ref="formRef"
        label-placement="left"
        :label-width="100"
        class="py-4"
      >
      <n-grid :cols="24" :x-gap="24">
        <n-form-item-gi :span="12" label="用户名" path="username">
          <n-input placeholder="请输入用户名" v-model:value="formParams.username" :readonly="usernameReadOnly"/>
        </n-form-item-gi>
        <n-form-item-gi :span="12" label="登录用户ID" path="userid">
          <n-input placeholder="请输入登录用户ID" v-model:value="formParams.userid" :readonly="useridReadOnly"/>
        </n-form-item-gi>
        <n-form-item-gi :span="12" label="登录密码" path="password">
          <n-input type="password" show-password-on="mousedown" placeholder="请输入登录密码" v-model:value="formParams.password" />
        </n-form-item-gi>
        <n-form-item-gi :span="12" label="再次输入登录密码" path="password_again">
          <n-input type="password" show-password-on="mousedown" placeholder="请再次输入登录密码" v-model:value="formParams.password_again" />
        </n-form-item-gi>
        <n-form-item-gi :span="12" label="手机号" path="phone">
          <n-input placeholder="请输入手机号" v-model:value="formParams.phone" />
        </n-form-item-gi>
        <n-form-item-gi :span="12" label="电子邮箱" path="email">
          <n-input placeholder="请输入电子邮箱" v-model:value="formParams.email" />
        </n-form-item-gi>
        <n-form-item-gi :span="12" label="角色" path="role">
          <n-select
            v-model:value="formParams.role"
            placeholder="请选择角色"
            :options="roleOptions"
            @update:value="ddd"
          />
        </n-form-item-gi>
        <n-form-item-gi :span="12" label="状态" path="status">
          <n-select
            v-model:value="formParams.status"
            placeholder="请选择状态"
            :options="statusOptions"
          />
        </n-form-item-gi>
      </n-grid>
    </n-form>
      <template #footer>
        <n-button type="primary" @click="saveuserinfo">
          提交
        </n-button>
      </template>

    </n-drawer-content>
  </n-drawer>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, ref,  h } from 'vue';
  import { useMessage } from 'naive-ui';
  import { BasicTable, TableAction } from '@/components/Table';
  import { getUserList, createUser, updateUser, deleteUser } from '@/api/system/user';
  import { columns } from './columns';
  import { PlusOutlined } from '@vicons/antd';
  import { type FormRules } from 'naive-ui';
  import { BasicForm, FormSchema, useForm } from '@/components/Form/index';

  const message = useMessage();
  const formRef: any = ref(null);
  const actionRef = ref();
  const showdrawer = ref(false);
  const formBtnLoading = ref(false);
  const titledrawer = ref('');
  const usernameReadOnly = ref(false);
  const useridReadOnly = ref(false);
  const schemas: FormSchema[] = [
      {
        field: 'name',
        component: 'NInput',
        label: '用户名',
        defaultValue: '',
        componentProps: {
            placeholder: '请输入用户名',
            onInput: (e: any) => {
                console.log(e);
            },
        },
      },
      {
        field: 'selectRole',
        component: 'NSelect',
        label: '角色',
        defaultValue: '',
        componentProps: {
            placeholder: '请选择角色',
            options: [
              {
                label: '管理员',
                value: '1',
              },
              {
                label: '普通用户',
                value: '0',
              },
            ],
            onUpdateValue: (e: any) => {
              console.log(e);
            },
          },
      },
      {
        field: 'selectStatus',
        component: 'NSelect',
        label: '状态',
        defaultValue: '',
        componentProps: {
            placeholder: '请选择状态',
            options: [
              {
                label: '禁用',
                value: '1',
              },
              {
                label: '启用',
                value: '0',
              },
            ],
            onUpdateValue: (e: any) => {
              console.log(e);
            },
          },
      },
];

  const [register, { getFieldsValue }] = useForm({
    gridProps: { cols: '3 s:3 m:4 l:5 xl:6 2xl:7' },
    labelWidth: 90,
    layout: 'inline',
    schemas,   
  });

  const formParams = reactive({
    id: 0,
    username: '',
    userid: '',
    password: '',
    password_again: '',
    phone: '',
    email: '',
    role: '',
    status: ''
  });  

  const roleOptions = reactive([
        {
          label: '管理员',
          value: '1'
        },
        {
          label: '普通用户',
          value: '0'
        }
      ]);
  const statusOptions = reactive([
        {
          label: '启用',
          value: '0'
        },
        {
          label: '禁用',
          value: '1'
        }
      ]);
  const rules: FormRules = {
    username: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入用户名',
    },
    userid: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入登录用户ID',
    },    
    password: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入登录密码',
    },
    password_again: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请再输入登录密码',
    },
    phone: {
      trigger: ['blur', 'input'],
      message: '请输入手机号',
    },
    role: {
      required: true,
      trigger: ['blur', 'change'],
      message: '请选择角色',
    }, 
    status: {
      required: true,
      trigger: ['blur', 'change'],
      message: '请选择状态',
    }, 
  };
  
  const actionColumn = reactive({
    width: 250,
    title: '操作',
    key: 'action',
    fixed: 'right',
    render(record) {
      return h(TableAction, {
        style: 'button',
        actions: [
          {
            label: '编辑',
            onClick: handleEdit.bind(null, record),
          },
          {
            label: '删除',
            onClick: handleDelete.bind(null, record),
          },
        ],
      });
    },
  });

  function ddd(value) {
    console.log('ddd:', formParams.role);
  }

  function showUserdrawer() {
    showdrawer.value = true;
    titledrawer.value = '新建用户';
    usernameReadOnly.value = false;
    useridReadOnly.value = false;
    formParams.username = '';
    formParams.userid = '';
    formParams.password = '';
    formParams.password_again = '';
    formParams.phone = '';
    formParams.email = '';
    formParams.role = '';
    formParams.status = '';
  }

  function saveuserinfo() {
    formBtnLoading.value = true;
    formRef.value.validate(async (errors) => {

      if (!errors) {
        if (formParams.password != formParams.password_again) {
          message.error('输入的密码不一致，请重新输入');
          return;
        }
        if (titledrawer.value == '编辑用户') {
          // 编辑用户
          const params = formParams;
          await updateUser(params);
          window['$message'].success('编辑成功');
        } else {
          // 创建用户
          const params = formParams;
          await createUser(params);
          window['$message'].success('新建成功');
        }
        setTimeout(() => {
          showdrawer.value = false;
          reloadTable();
        });
      } else {
        window['$message'].error('请输入完整信息');
      }

      formBtnLoading.value = false;
    });
  }

  const loadDataTable = async (res) => {
    const data = await getUserList({ ...getFieldsValue(), ...res });
    console.log('**** data=', data);
    return data;
  };

  function handleSubmit(values: Recordable) {
    console.log(values);
    reloadTable();
  }

  function handleReset(values: Recordable) {
    console.log(values);
  }

  function onCheckedRow(rowKeys: any[]) {
    console.log(rowKeys);
  }

  function reloadTable() {
    actionRef.value.reload();
  }

  function handleEdit(record: Recordable) {
    showdrawer.value = true;
    titledrawer.value = "编辑用户";
    usernameReadOnly.value = true;
    useridReadOnly.value = true;
    formParams.id = record.id;
    formParams.username = record.username;
    formParams.userid = record.userid;
    formParams.password = record.password;
    formParams.password_again = record.password;
    formParams.phone = record.phone;
    formParams.email = record.email;
    formParams.role = record.role;
    formParams.status = record.status;
  }

  function handleDelete(record: Recordable) {
    const $dialog = window['$dialog'];
    const msg = "您确定要删除'" + record.username + "'用户信息吗？"
    $dialog.info({
          title: '提示',
          content: msg,
          positiveText: '确定',
          negativeText: '取消',
          onPositiveClick: async () => {
            // 删除用户
            formParams.id = record.id;
            const params = formParams;
            await deleteUser(params);
            window['$message'].success('删除成功');
            setTimeout(() => {
              reloadTable();
            });
          },
          onNegativeClick: () => {},
        });
  }

</script>

<style lang="less" scoped></style>
